<template>
  <Dialog v-model="dialogVisible" title="用户选择" width="80%" maxHeight="350px">
    <div class="announcement-dialog-search">
      <el-form :inline="true" :model="formInline" class="demo-form-inline" ref="formRef">
        <el-form-item label="账号：" prop="username">
          <el-input v-model="formInline.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-select v-model="formInline.sex" clearable>
            <el-option
              :label="item.label"
              :value="item.value"
              :key="index"
              v-for="(item, index) in sexOptions"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="生日：" prop="sex">
          <el-date-picker v-model="formInline.birthday" type="date" placeholder="请选择" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm(formRef)">
            <span style="vertical-align: middle">查询</span>
          </el-button>
          <el-button type="primary" @click="resetForm(formRef)">
            <span style="vertical-align: middle">重置</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="announcement-dialog-table">
      <div class="left">
        <!-- @selection-change="handleSelectionChange"-->
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          height="250"
          border
          @select="handleSelect"
          @select-all="handleSelectAll"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column property="realname" label="姓名" />
          <el-table-column property="username" label="账号" />
          <el-table-column property="phone" label="电话" />
          <el-table-column property="birthday" label="出生日期" />
        </el-table>
        <!-- <el-pagination
          v-model:current-page="searchParams.pageNo"
          v-model:page-size="searchParams.pageSize"
          :page-sizes="[5, 10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        /> -->
      </div>
      <div class="right">
        <el-table :data="selectUsers" border height="250">
          <el-table-column property="realname" label="姓名" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button link type="primary" size="small" @click.prevent="deleteRow(scope.$index)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <template #footer>
      <ElButton type="primary" :loading="loading" @click="save">
        {{ t('RoleManage.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('RoleManage.close') }}</ElButton>
    </template>
  </Dialog>
</template>
<script setup lang="ts" name="Dialog">
import { ref, reactive, watch, nextTick } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { Dialog } from '@/components/Dialog'
import { userListApi } from '@/api/userManage/index'
import { filterParams } from '@/utils'
const emit = defineEmits(['update:users'])
const props = defineProps({
  users: {
    type: Array,
    default: () => []
  }
})
const dialogVisible = ref(false)
// 查询表格
// const pagination = ref({
//   pageNo: 1,
//   pageSize: 5,
//   total: 0
// })
// let totals = ref(0)

// *************************回显选中状态**************************
const EchoChecked = async () => {
  await nextTick()
  if (tableData.value.length && props.users.length) {
    // @ts-expect-error
    const ids = props.users.map((item) => item.id)
    for (var i = 0; i < tableData.value.length; i++) {
      // @ts-expect-error
      if (ids.includes(tableData.value[i].id)) {
        multipleTableRef.value!.toggleRowSelection(tableData.value[i], true)
      }
    }
  }
}
// *************************请求接口**************************
const getUserList = async (params) => {
  let rst = await userListApi(params)
  // let res = rst.result
  // searchParams.pageNo = current
  // searchParams.pageSize = size
  // totals.value = total
  rst.result.records.forEach((item, i) => {
    // @ts-expect-error
    item.index = i
    // @ts-expect-error
    item.label = item.realname
    // @ts-expect-error
    item.value = item.id
  })
  // @ts-expect-error
  tableData.value = rst.result.records
  EchoChecked()
}
const searchParams = reactive({
  column: 'createTime',
  order: 'desc',
  field: 'id,,realname,username,phone,birthday',
  pageNo: 1,
  pageSize: -1
})
getUserList(searchParams)
const loading = ref(false)
// 性别下拉
const sexOptions = [
  { label: '男', value: '1' },
  { label: '女', value: '2' }
]
const formInline = ref({
  username: '',
  sex: '',
  birthday: ''
})
const formRef = ref()
// 查询表单
const submitForm = async (formEl) => {
  if (!formEl) return
  Object.assign(searchParams, filterParams(formInline.value))
  getUserList(searchParams)
  console.log('提交', searchParams)
}
// 重置表单
const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
// table 数据
const multipleTableRef = ref()
const tableData = ref([])
// const multipleSelection = ref([]) // 复选框选中数据
// table 右侧数据
// const tableRData = ref([])

// 表格复选框操作数据
// const handleSelectionChange = (val) => {
//   console.log(val, '-----')
//   multipleSelection.value = val
//   tableRData.value = multipleSelection.value
// }
// // 分页操作数据
// const handleSizeChange = (val: number) => {
//   searchParams.pageSize = val
//   getUserList(searchParams)
// }
// const handleCurrentChange = (val: number) => {
//   console.log(val, 'val---')
//   searchParams.pageNo = val
//   getUserList(searchParams)
// }
// 右侧表格删除数据
const deleteRow = (val) => {
  selectUsers.value.splice(val, 1)
}
const { t } = useI18n()
// const dialogProps = ref({})
const save = () => {
  dialogVisible.value = false
}

// 接收父组件传过来的参数
const acceptParams = (params) => {
  //   dialogProps.value = params
  dialogVisible.value = params
}

defineExpose({
  acceptParams
})
//****************************分页****************************/
// let selectUsers = ref<{ [key: string]: any }[]>([])
let selectUsers = ref<unknown[]>([])
const handleSelect = (data) => {
  selectUsers.value = data
}
const handleSelectAll = (data) => {
  if (data.length) {
    handleSelect(data)
  } else {
    selectUsers.value = []
  }
}

watch(
  () => props.users,
  (val) => {
    selectUsers.value = val
  }
  // { immediate: true } // 编辑回显需要
)
// 编辑回显需要
watch(
  () => tableData.value,
  async (val) => {
    await nextTick()
    // @ts-expect-error
    selectUsers.value = val.filter((item) => props.users.includes(item.id))
  }
)
watch(
  () => dialogVisible.value,
  (val) => {
    if (val) {
      EchoChecked()
    }
  }
)
watch(
  () => selectUsers.value,
  (val) => {
    emit('update:users', val)
  },
  {
    deep: true
  }
)
</script>
<style scoped lang="less">
.announcement-dialog-table {
  display: flex;
  .left {
    width: 70%;
  }
  .right {
    width: 28%;
    .el-table {
      margin-left: 10px;
    }
  }
}
</style>
